﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TweetSharp;

namespace BankProject.Views
{
    public partial class TwitterPage : PhoneApplicationPage
    {
        private const string consumerKey = "eH36i3QHl3Qxp4eYc8HEQ";
        private const string consumerSecret = "tqyIwxoIZ8dpjZ4814Ku2lma7apTdmmslUVRT8lmUs";
        //TwitterService client;
        private OAuthRequestToken requestToken;
        
        public TwitterPage()
        {
            InitializeComponent();
            App.ViewModel.userAuthenticated = false;
            App.ViewModel.CLient = new TwitterService(consumerKey, consumerSecret);//инициализация приложения
            App.ViewModel.CLient.GetRequestToken(processRequestToken);
        }


        private void processRequestToken(OAuthRequestToken token, TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error getting request token"); });
            else
            {
                requestToken = token;
                Dispatcher.BeginInvoke(() =>
                {
                    brouser2.Visibility = System.Windows.Visibility.Visible;
                    brouser2.Navigate(App.ViewModel.CLient.GetAuthorizationUri(requestToken));
                });
            }
        }

        

        // From Hammock.Extensions.StringExtensions.cs
        public static IDictionary<string, string> ParseQueryString(string query)
        {
            // [DC]: This method does not URL decode, and cannot handle decoded input
            if (query.StartsWith("?")) query = query.Substring(1);
            if (query.Equals(string.Empty))
            {
                return new Dictionary<string, string>();
            }
            var parts = query.Split(new[] { '&' });
            return parts.Select(
                part => part.Split(new[] { '=' })).ToDictionary(
                    pair => pair[0], pair => pair[1]
                );
        }

        private void processAccessToken(OAuthAccessToken token, TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); });
            else
            {
                App.ViewModel.CLient.AuthenticateWith(token.Token, token.TokenSecret);
                App.ViewModel.userAuthenticated = true;
                //Send the Tweet, we will add this code later
            }
        }

        private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
        {
            if (response.StatusCode == HttpStatusCode.OK)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); });
            else
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); });
        }

        private void brouser2_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("oauth_verifier"))
            {
                var values = ParseQueryString(e.Uri.AbsoluteUri);
                string verifier = values["oauth_verifier"];
                App.ViewModel.CLient.GetAccessToken(requestToken, verifier, processAccessToken);
                Dispatcher.BeginInvoke(() => { brouser2.Visibility = System.Windows.Visibility.Collapsed; });
            }
        }
        
    }
}